package ltd.itlover.yqblog.blog;


import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sackcentury.shinebuttonlib.ShineButton;

import org.litepal.crud.DataSupport;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import dagger.hilt.android.HiltAndroidApp;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import ltd.itlover.yqblog.R;
import ltd.itlover.yqblog.dto.Result;
import ltd.itlover.yqblog.entity.BlogListBrief;
import ltd.itlover.yqblog.network.BlogApiService;
import ltd.itlover.yqblog.utils.TokenUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ru.noties.markwon.Markwon;

@AndroidEntryPoint
@SuppressWarnings("all")
public class BlogDetailActivity extends AppCompatActivity {
    @Inject
    BlogApiService blogApiService;

    private ImageView avatarImg;
    private TextView textBlogTitle;
    private TextView textUserName;
    private TextView textCategoryName;
    private ShineButton shineButtonLike;
    private ShineButton shineButtonCollect;
    private TextView like_btn_text;
    private TextView collect_btn_text;
    private BlogListBrief blogListBrief;
    private TextView textContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        requestDataFromInternet();

        bindLikeEventToShine();
    }


    //获得各种控件的实体对象并渲染已有的数据
    private void init(){
        setContentView(R.layout.activity_blog_detail);
        blogListBrief = (BlogListBrief) getIntent().getSerializableExtra("blogDetail");
        Log.i("信息", blogListBrief.toString());
        textBlogTitle = (TextView) findViewById(R.id.text_blog_detail_title);
        avatarImg = (ImageView) findViewById(R.id.img_avatar);
        textUserName = (TextView) findViewById(R.id.text_detail_username);
        shineButtonLike = (ShineButton) findViewById(R.id.bt_like);
        shineButtonCollect = (ShineButton) findViewById(R.id.bt_star);
        like_btn_text = (TextView) findViewById(R.id.like_btn_label);
        collect_btn_text = (TextView) findViewById(R.id.collect_btn_label);
        textCategoryName = (TextView) findViewById(R.id.text_category_name);
        textContent = (TextView) findViewById(R.id.text_content);
        if(blogListBrief != null) {
            textBlogTitle.setText(blogListBrief.getTitle().toString());
            textUserName.setText(blogListBrief.getUsername().toString());
            textCategoryName.setText(blogListBrief.getCategoryName().toString());
            Glide.with(this).load(TokenUtil.getImgDomain()+blogListBrief.getAvatar())
                    .error(R.drawable.default_avatar).into(avatarImg);
        }
    }

    private void requestDataFromInternet(){
        blogApiService.getBlogDetail(blogListBrief.getBlogId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<BlogListBrief>>() {
                    @Override
                    public void accept(Result<BlogListBrief> blogListBriefResult) throws Exception {
                        BlogListBrief b = blogListBriefResult.getData();
                        blogListBrief.setContent(b.getContent());
                        blogListBrief.setIfLiked(b.getIfLiked());
                        blogListBrief.setIfCollected(b.getIfCollected());

                        //将申请到的数据保存到数据库
                        blogListBrief.update(blogListBrief.getId());
                        loadDataToPage();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        makeInfo("网络请求失败");
                        loadDataToPage();
                    }
                });
    }

    public void makeInfo(String info){
        Toast.makeText(this.getApplicationContext(), info, Toast.LENGTH_SHORT).show();
    }

    public void setLikeBtnStatus(boolean res){
        shineButtonLike.setChecked(res);
        like_btn_text.setText(res ? "已点赞" : "点赞");
        like_btn_text.setTextColor(Color.parseColor(res ? "#FF6666" : "#1e1e1e"));
    }

    public void setCollectBtnStatus(boolean res){
        shineButtonCollect.setChecked(res);
        collect_btn_text.setText(res ? "已收藏" : "收藏");
        collect_btn_text.setTextColor(Color.parseColor(res ? "#FF6666" : "#1e1e1e"));
    }

    public void loadDataToPage(){
        BlogListBrief blogListBrief1 = DataSupport.find(BlogListBrief.class, blogListBrief.getId());
        if (blogListBrief1 != null){
            blogListBrief = blogListBrief1;
        }

        String content = blogListBrief.getContent();
        content = content == null ? "":content;

        Markwon.setMarkdown(textContent, content);
        setLikeBtnStatus(blogListBrief.isIfLiked());
        setCollectBtnStatus(blogListBrief.isIfCollected());
    }

    private void like() {
        blogApiService.likeABlog(blogListBrief.getBlogId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> stringResult) throws Exception {
                        makeInfo("点赞成功");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        makeInfo("网络请求错误, 点赞失败");
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                });
    }
    private void cancelLike() {
        blogApiService.cancelLikeABlog(blogListBrief.getBlogId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> stringResult) throws Exception {
                        makeInfo("取消点赞成功");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        makeInfo("网络请求错误, 取消点赞失败");
                    }
                });
    }

    private void bindLikeEventToShine(){
        shineButtonLike.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(View view, boolean checked) {
                if(checked){
                    like();
                }
                else{
                    cancelLike();
                }
                setLikeBtnStatus(checked);
            }
        });
    }
}